#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       FiWeathersrc.py
#       
#       Copyright 2010-2011 Aleksi Joakim Palomäki <aleksi@ajp.dy.fi>, Tuukka Ojala <tuukka.ojala@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 3 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

'''
This is function to find the informations Today
'''


def cityString (title, doc):
	start = int (title) +7
	end = doc.find (" - Pai")
	return doc [start:end]


def finds(location):
	import config_parser
	cfg = "ITL.txt"
	c = config_parser.config_pars(cfg)

	baseurl = c["baseurl"]
	
	tempera_num = int(c["temperature_num"])
	tempera_base = c["temperature_start"]

	dew_num = int(c["dewpoint_num"])
	dew_base = c["dewpoint_start"]
	
	hum_num = int(c["humidity_num"])
	hum_base = c["humidity_start"]
	
	win_num = int(c["wind_speed_num"])
	win_base = c["wind_speed_start"]
	
	wing_num = int(c["wind_gust_num"])
	wing_base = c["wind_gust_start"]

	import string_num_finder
	x = string_num_finder.numfind()
	''''List for conditions that this function returns'''
	Conditions=[]
	
	'''Imports'''
	import urllib2
	
	'''Open the weatherinstitute webpage and fetch the source html'''
	try:
		site = baseurl + location
		url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':'))
	except :
		print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list"
		exit()
	doc=url.read()
	
	'''City name'''
	title = doc.find ("<title>")
	if title > 0:
		Conditions.append (cityString (title, doc))
	else:
		Conditions.append ("Unknown city")

	'''Temperature value'''
	temper = x.numfinder(doc, tempera_base, tempera_num)
	if temper > 0:
		Conditions.append(temper)
        else:
                Conditions.append("No information.")

	'''Dew Point value'''
	dew = x.numfinder(doc, dew_base, dew_num)
	if dew > 0:
		#print dew
		Conditions.append(dew)
        else:
                Conditions.append("No information.")
	
	'''Humidity value'''
	humidit =x.numfinder(doc, hum_base, hum_num)
	if humidit > 0:
		Conditions.append(humidit)
		
	'''Windspeed value'''
	windit =x.numfinder(doc, win_base, win_num)
	clear = doc.find('''Tyynt&auml;</span>''') #dependant on working with ITL fix it.
	if windit > 0:
		Conditions.append(windit)
	elif clear > 0:
		Conditions.append('Calm')
	else:
		Conditions.append("No information.")

	'''Wind gust value'''
	gust =x.numfinder(doc, wing_base, wing_num)
	if gust > 0:
		Conditions.append(gust)	
	else:
		Conditions.append("No information.")


	'''Cloudness'''
	clouds =x.numfinder(doc, '''<span class="parameter-value">(''', 50)
	if clouds > 0:
		Conditions.append(clouds)	
	else:
		Conditions.append("No information.")

	'''Visibility'''
	visibility =x.numfinder(doc, '''<span class="parameter-name">N&auml;kyvyys</span>''', 100)
	if visibility > 0:
		Conditions.append(visibility)	
	else:
		Conditions.append("No information.")

	'''pressure'''
	pr = x.numfinder(doc, '''<span class="parameter-name">Paine</span>
<span class="parameter-value">''', 80)
	if pr > 0:
		Conditions.append (pr)
	else:
		Conditions.append ("No information.")

	'''Water for hour'''
	wh = x.numfinder(doc, '''sadekertym&auml;</span>
<span class="parameter-value">''', 90)
	#print wh
	if wh > 0:
		Conditions.append (wh)
	else:
		Conditions.append ("No information.")

	return Conditions


###The Ugliest thing i ever wrote.. well not quite.. but close!###

def forec(location):
	'''Imports'''
	import urllib2
	import datetime
	'''Open the weatherinstitute webpage and fetch the source html'''
	try:
		site = 'http://ilmatieteenlaitos.fi/saa/' + location
		url = urllib2.urlopen(urllib2.quote(site).replace('%3A', ':'))
	except :
		print "Unable to fetch weather data. Please check your internet connection. If your connection is working fine then please file a bug at http://code.google.com/p/fiweather/issues/list"
		exit()
	doc=url.read()
	begin = doc.find('<tr class="meteogram-temperatures">')
	times = doc.find('<colgroup>')
	#return begin
	if begin > 0:
		
		loppu = doc.find('</td></tr><tr class="meteogram-wind-symbols"') 
		#print doc[begin:loppu]
		parse1 = doc[begin:loppu].replace('<tr class="meteogram-temperatures">', '').replace('\n            <td class="positive">','').replace('</td><td class="positive">', '').replace('                ', '').replace('<span title="lämpötila ', '').replace('</span>', '')
		parse2 = parse1.split('\n')
		lista = []
		
		for f in parse2:
			luku = f.find('"')
			parsettu = f[0:luku].replace('°C', '')
			lista.append(parsettu)

		#lista= list(set(lista))
		lista.remove("")
		for x in lista:
			if x == '             ':
				lista.remove(x)
			else:
				pass

	if times > 0:
		begin = doc.find('<colgroup>')
		end = doc.find('</colgroup>')
		parse1 = doc[begin:end]
		parse2 = parse1.replace('          <col class="', '').replace('        <col class="', '').replace(' first-daily-step" />', '').replace(' last-daily-step" />', '').replace('" /', '').replace('>', '')
		parse3 = parse2.split('\n')
		parse3.remove("<colgroup")
		parse3.remove('          ')
		fir = 0
		o = parse3.count('first-day odd-day ')
		luku = 0
		i = 0
		import forec
		o = forec.forec(lista, parse3)
		return o
		
	else:
		return 'Something went wrong in FiWeathersrc.py '
